function [] = tabulateCounterResults( counterfactuals, rowLabels, filename)
% This function tabulates the average costs calculated from the model along
% with cost breakdowns from IRENA and CERC

%% Aggregate emissions across periods

% Put all counterfactual outcomes into a single table
C = length(counterfactuals);
outTable = counterfactuals{1}.output_tk;
outTable.cid = ones(height(outTable),1);
for c = 2:C
    cTable = counterfactuals{c}.output_tk;
    cTable.cid = c*ones(height(cTable),1);
    outTable = vertcat(outTable,cTable);
end
    
% Aggregate emissions within scenario-period-emissions levels
outTableAgg = grpstats(outTable,{'cid','id_level'},{'mean'},...
    'datavars',{'Et','Zt','Pt'});
outTableAgg = sortrows(outTableAgg,{'cid','id_level'},{'ascend','ascend'});

outTableAgg.Et = round(outTableAgg.mean_Et / 1e3,0);
outTableAgg.Zt = round(outTableAgg.mean_Zt / 1e6,2);
outTableAgg.Scaled_Cap = outTableAgg.id_level / 1e3;

% Convert table from long to wide format for different emissions levels
outTableWide = unstack(outTableAgg,...
    {'mean_Pt','Zt'},{'Scaled_Cap'},'GroupingVariables','cid');
outTableWide = movevars(outTableWide,'Zt_x170','After','mean_Pt_x170');
outTableWide = removevars(outTableWide,'cid');
outTable     = outTableWide;

% Add comparison Cols
outTable.Zt_del170 = 100*((outTable.Zt_x170 / outTable.Zt_x170(1)) - 1);
outTable.Zt_del240 = 100*((outTable.Zt_x240 / outTable.Zt_x240(1)) - 1);
outTable = movevars(outTable,'Zt_del170','After','Zt_x170');
outTable = movevars(outTable,'Zt_del240','After','Zt_x240');

% Add CC row group
outTable = outTable([1:2,2:end], :); 
outTable{2,:} = Inf;

%% Construct table

% Metadata
outTable.Properties.VariableDescriptions = ...
    {'Price','Cost','$\Delta$Cost','Price','Cost','$\Delta$Cost'};
outTable.Properties.VariableUnits = ...
    {'(INR/kg)','(INR m)','(\%)','(INR/kg)','(INR m)','(\%)'};
outTable.Properties.RowNames = rowLabels;
 
% Convert table contents to appropriately formatted strings
outTable = convertvars(outTable,1:width(outTable),'string');
for r = 1:height(outTable)
    for c = 1:width(outTable)
        if strcmp(outTable{r,c},"Inf")
            outTable{r,c} = "";
        else if strcmp(outTable{r,c},"0")
            outTable{r,c} = "--";
        else
            outTable{r,c} = string(sprintf('%1.1f',double(outTable{r,c})));
    end
        end
        
    end
end

% Add appropriate percent symbols
for r = 1:height(outTable)
    for c = [3 6]
        if ~strcmp(outTable{r,c},"") && ~strcmp(outTable{r,c},"--")
            outTable{r,c} = strcat(outTable{r,c}, '\%');
        end
    end
end

display(outTable);

% Meta-header for columns
metaheader = {...
    '& \\multicolumn{3}{c}{Emissions = 170 tons} & \\multicolumn{3}{c}{Emissions = 240 tons}\\\\\n', ...
    '\\cmidrule(lr){2-4} \\cmidrule(lr){5-7}'};

% Output
if contains(filename, "Table_")
    latexTable(outTable,filename,metaheader);
end

end
